﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using Microsoft.Extensions.Hosting;
using Single.Core.Aop;
using Single.Core.Service;
using System.Reflection;

namespace Single.Autofac
{
    public static class AutofacExtensions
    {
        public static IHostBuilder UseAutofacExtensions(this IHostBuilder builder)
        {
            builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());

            builder.ConfigureContainer<ContainerBuilder>((context, builder) =>
            {
                builder.RegisterType<ServiceInterceptor>();

                var assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies();

                Type serviceType = typeof(ServiceDependency);
                List<Type> types = new List<Type>();

                foreach (var assembly in assemblies)
                {
                    try
                    {
                        types.AddRange(Assembly.Load(assembly).GetTypes().Where(m => m.IsAssignableTo(serviceType) && !m.IsAbstract));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(assembly.Name + ex.Message);
                    }
                }

                builder.RegisterTypes(types.ToArray()).InstancePerLifetimeScope().EnableClassInterceptors().InterceptedBy(typeof(ServiceInterceptor));
            });

            return builder;
        }
    }
}